package com.treasure.service.user.controller;

import com.alibaba.fastjson.JSON;
import com.treasure.service.annotation.LogInfo;
import com.treasure.service.commons.lang.util.BeanUtil;
import com.treasure.service.commons.lang.util.IdCreater;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.domain.TUserInfo;
import com.treasure.service.dto.PrepareResult;
import com.treasure.service.dto.TUserInfoDto;
import com.treasure.service.enums.RedisKeys;
import com.treasure.service.listener.process.BizInformationPushForWechatOrSmsProcess;
import com.treasure.service.result.ResponseResult;
import com.treasure.service.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
* @Description:    用户基本信息管理
* @Author:         panxinwen
* @CreateDate:     2018/10/15 21:13
* @Version:        1.0
*/
@Api(value = "用户基本信息维护",description = "用户个人信息维护，包括微信信息，实名信息，个人基本信息")
@RestController
@RequestMapping("/userInfo/v1")
public class UserInfoController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BizInformationPushForWechatOrSmsProcess creditCardTransactionResultProcess;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @LogInfo(log = "公众号创建用户",isPrint = true)
    @PostMapping("/createWechatUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "用户在公众号唯一编号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nickname", value = "昵称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "wNickname", value = "微信昵称", required = false, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "headimgurl", value = "自定义头像", required = false, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "wHeadimgurl", value = "微信头像", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", required = false, dataType = "String", paramType = "query"),
    })
    public ResponseEntity<TUserInfoDto> createWechatUser(@RequestBody TUserInfo user) throws UnsupportedEncodingException {

        user.setUserId(IdCreater.getLongId());
//        user.setNickname(URLEncoder.encode(user.getNickname(), GlobalConstant.ENCODING_UTF8));
//        user.setwNickname(URLEncoder.encode(user.getNickname(), GlobalConstant.ENCODING_UTF8));
//        user.setNickname(user.getNickname());
//        user.setwNickname(user.getNickname());
        user.setJoinTime(new Date());
        user.setLastLoginTime(new Date());
        user.setIsAttention(1);
        user.setIsAuthName(false);
        user.setIsBindingBankcard(false);
        user.setIsSetPayPwd(false);
        user.setIsBindingEmail(false);
        user.setStatus(1);
        user.setIsMember(0);
        user.setWealthValue(0l);
        user.setGrade(0);
        //生成邀请码
        long currentAmt = redisTemplate.opsForValue().increment(RedisKeys.INVITE_CODE.build(), 1)+1000000l;
        user.setSelfInviteCode(currentAmt+"");
        userInfoService.add(user);
        return  ResponseEntity.ok(BeanUtil.copy(user,TUserInfoDto::new));

    }


    @LogInfo(log = "更新用户信息",isPrint = true)
    @PostMapping("/updateUserInfo")
    public ResponseEntity updateUserInfo(@RequestBody TUserInfo info) throws UnsupportedEncodingException {
//        info.setNickname(URLEncoder.encode(info.getNickname(), GlobalConstant.ENCODING_UTF8));
//        info.setwNickname(URLEncoder.encode(info.getNickname(), GlobalConstant.ENCODING_UTF8));
//        info.setwHeadimgurl(URLEncoder.encode(info.getHeadimgurl(), GlobalConstant.ENCODING_UTF8));
//        info.setHeadimgurl(URLEncoder.encode(info.getHeadimgurl(), GlobalConstant.ENCODING_UTF8));
        info.setNickname(info.getNickname());
        info.setwNickname(info.getNickname());
        info.setwHeadimgurl(info.getHeadimgurl());
        info.setHeadimgurl(info.getHeadimgurl());
        info.setLastLoginTime(new Date());
        TUserInfoDto tUserInfoDto = userInfoService.updateUserInfo(info);

        return ResponseEntity.ok(tUserInfoDto);

    }

    @LogInfo(log = "获取用户信息",isPrint = true)
    @PostMapping("/getUserInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "openId", value = "用户在公众号唯一编号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phonenumber", value = "绑定手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cardNumber", value = "身份证号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "被邀请邀请码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", paramType = "query"),
    })
    public ResponseEntity getUserInfo(@RequestBody TUserInfo info){

        TUserInfoDto infoDto = userInfoService.getUserInfo(info);

        return  ResponseEntity.ok(infoDto);

    }

    @LogInfo(log = "购买会员（预购买）",isPrint = true)
    @PostMapping("/dredgeMember")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "memberGrade", value = "会员等级 1-创业者 2-创业家 3-合伙人", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "couponId", value = "优惠券编号", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "clientIp", value = "调用客户端ip", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "payType", value = "支付方式(1:微信支付)", required = false, dataType = "Long", paramType = "query")
    })
    public ResponseEntity dredgeMember(
            @RequestParam(value = "userId", required = true) Long userId,
            @RequestParam(value = "couponId", required = false) Long couponId,
            @RequestParam(value = "memberGrade", required = false) Integer memberGrade,
            @RequestParam(value = "clientIp", required = false) String clientIp,
            @RequestParam(value = "payType", required = false,defaultValue = "1") Integer payType
    ){

        PrepareResult prepareResult = userInfoService.dredgeMember(userId,memberGrade,couponId,payType,clientIp);

        return ResponseEntity.ok(prepareResult);
    }

    @LogInfo(log = "会员购买确认回调",isPrint = true)
    @PostMapping("/dredgeMemberCallBack")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bizId", value = "申请开通业务号", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "申请开通状态", required = false, dataType = "Long", paramType = "query")
    })
    public ResponseEntity dredgeMemberCallBack(
            @RequestParam(value = "bizId", required = true) Long bizId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "userId", required = false) Long userId
    ){

        userInfoService.dredgeMemberCallBack(bizId,userId,status);

        return ResponseEntity.ok("ok");
    }

    @LogInfo(log = "建立邀请关系",isPrint = true)
    @PostMapping("/bindingRelation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "被邀请人", required = false, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请人邀请码", required = false, dataType = "Long", paramType = "query")
    })
    public ResponseEntity bindingRelation(
            @RequestParam(value = "openId", required = true) String openId,
            @RequestParam(value = "inviteCode", required = false) String inviteCode
    ) throws UnsupportedEncodingException {

        userInfoService.bindingRelation(openId,inviteCode);

        return ResponseEntity.ok("ok");
    }

    @LogInfo(log = "用户注册或登录",isPrint = true)
    @PostMapping("/registerAndLogin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phonenumber", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, dataType = "Long", paramType = "query")
    })
    public ResponseEntity<TUserInfoDto> registerAndLogin(@RequestBody TUserInfo user) {

        logger.info("注册或登录用户信息：{}",JSON.toJSONString(user));

        if (user.getUserId() == null){

            TUserInfo suser = new TUserInfo();
            suser.setPhonenumber(user.getPhonenumber());
            //查询用户是否已经注册
            TUserInfoDto tUserInfoDto = userInfoService.getUserInfo(suser);
            //如果已经注册就登录
            if (tUserInfoDto != null && tUserInfoDto.getUserId() != null){
                logger.info("用户id为空但是手机号已注册直接登录：{}",JSON.toJSONString(tUserInfoDto));
                return ResponseEntity.ok(tUserInfoDto);
            }
            if (StringUtil.isNotEmpty(user.getInviteCode())){
                TUserInfo tUserInfo = new TUserInfo();
                tUserInfo.setInviteCode(user.getInviteCode());
                TUserInfoDto dto = userInfoService.getUserInfo(tUserInfo);
                user.setInviteCode((dto==null||dto.getUserId()==null)?null:dto.getUserId());
            }
            user.setUserId(IdCreater.getLongId());
            user.setJoinTime(new Date());
            user.setLastLoginTime(new Date());
            user.setIsAttention(1);
            user.setIsAuthName(false);
            user.setIsBindingBankcard(false);
            user.setIsSetPayPwd(false);
            user.setIsBindingEmail(false);
            user.setStatus(1);
            user.setIsMember(0);
            user.setWealthValue(0l);
            user.setGrade(0);
            //生成邀请码
            long currentAmt = redisTemplate.opsForValue().increment(RedisKeys.INVITE_CODE.build(), 1)+1000000l;
            user.setSelfInviteCode(currentAmt+"");
            userInfoService.add(user);
            TUserInfoDto dto = BeanUtil.copy(user,TUserInfoDto::new);
            logger.info("用户id为空但是手机号未注册创建用户并登录：{}",JSON.toJSONString(dto));
            return  ResponseEntity.ok(dto);
        }else {
            // Todo 查询手机号是否已经绑定
            TUserInfo suser = new TUserInfo();
            suser.setPhonenumber(user.getPhonenumber());
            //查询用户是否已经注册
            TUserInfoDto tUserInfoDto = userInfoService.getUserInfo(suser);

            if (tUserInfoDto != null  && tUserInfoDto.getUserId() != null){


                //手机号已经注册说明需要将注册的手机号绑定到公众号上
                /**
                 * 手机号已经注册说明需要将注册的手机号绑定到公众号上
                 * 1、查询公众号账号
                 * 2、更新公众号信息到手机号账号
                 * 3、删除公众号账号
                 */
                TUserInfo info =userInfoService.getUserInfoByUserId(user.getUserId());
                info.setUserId(tUserInfoDto.getUserId());
                TUserInfoDto result = userInfoService.updateUserInfo(info);
                if (result != null){
                    userInfoService.removeUserInfo(user.getUserId());
                }
                return ResponseEntity.ok(result);
            }

            TUserInfoDto dto = BeanUtil.copy(userInfoService.bindingPhonenumber(user.getPhonenumber(),user.getUserId()),TUserInfoDto::new);
            logger.info("用户id不为空绑定手机号并登录：{}",JSON.toJSONString(dto));
            return  ResponseEntity.ok(dto);
        }

    }

    @LogInfo(log = "完善个人信息",isPrint = true)
    @ApiOperation(value = "完善个人信息", notes = "完善个人信息")
    @PostMapping("/perfectInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardNumber", value = "身份证", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cardName", value = "姓名", required = false, dataType = "String", paramType = "query")
    })
    public ResponseEntity perfectInfo(@RequestBody TUserInfo user){
        ResponseResult result = userInfoService.perfectInfo(user);
        return ResponseEntity.ok(result);
    }

//    @LogInfo(log = "发送消息模板",isPrint = true)
//    @ApiOperation(value = "发送消息模板", notes = "发送消息模板")
//    @PostMapping("/creditCardTransactionResultProcess")
//    public ResponseEntity creditCardTransactionResultProcess(){
//        return ResponseEntity.ok(creditCardTransactionResultProcess.process());
//    }

}
